#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#define pathname "/practice/lesson-test/pro_communication/sharedmem"
#define proj_id 0x6666
#define size 4096
#define FIFO_FILE "./myfifo"
#define MODE 0666
#define N 1024
using namespace std;

enum
{
    FIFO_ERROR = 1,
    UNLINK_ERROR,
    OPEN_ERROR,
    READ_ERROR,
    FTOK_ERROR,
    SHMGET_ERROR
};

class Init
{
public:
    Init()
    {
        // 创建命名管道
        int ret = mkfifo(FIFO_FILE, MODE);
        if (ret == -1)
        {
            perror("mkfifo");
            exit(FIFO_ERROR);
        }
    }

    ~Init()
    {
        // 移除命名管道
        int m = unlink(FIFO_FILE);
        if (m == -1)
        {
            perror("unlink");
            exit(UNLINK_ERROR);
        }
    }
};

key_t getKey()
{
    int key = ftok(pathname, proj_id);
    if (key == -1)
    {
        perror("ftok");
        exit(FTOK_ERROR);
    }
    return key;
}

int getshmidHelper(int shmflg)
{
    key_t key = getKey();
    int shmid = shmget(key, size, shmflg);
    if (shmid == -1)
    {
        perror("shmget");
        exit(SHMGET_ERROR);
    }
    return shmid;
}

int creatshmflg()
{
    return getshmidHelper(IPC_CREAT | IPC_EXCL | 0666);
}

int getshmflg()
{
    return getshmidHelper(IPC_CREAT);
}
